package com.itheima.activiti.listener;

import com.itheima.activiti.entity.business.Leaves;
import com.itheima.activiti.service.business.LeaveService;
import com.itheima.activiti.service.system.UserService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.history.HistoricProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * 直属上级
 */
@Component
@Slf4j
public class TaskLeaveSuperiorListener implements TaskListener {

    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private UserService userService;
    @Autowired
    private LeaveService leaveService;

    @Override
    public void notify(DelegateTask delegateTask) {
        log.info("获取上级领导监听器 : {} assignee : {}", delegateTask.getId(), delegateTask.getAssignee());
        if (StringUtils.isNotBlank(delegateTask.getAssignee())) {
            log.info("流程已存在处理人，无需动态分配");
            return;
        }
        HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(delegateTask.getProcessInstanceId()).singleResult();
        String startUser = processInstance.getStartUserId();
        log.info("获取发起人：{}", startUser);
        String nextAssignee = userService.getSuperior(startUser);
        if(null == nextAssignee){   //如果没有上级审批人，按照流程图的需要，则需要重新再审批一次
            nextAssignee = startUser;
        }
        log.info("获取上级领导 : {}", nextAssignee);
        taskService.setAssignee(delegateTask.getId(), nextAssignee);
        String businessId = processInstance.getBusinessKey();
        Leaves leaves = leaveService.getById(businessId);
        log.info("设置参数 duration : {}", leaves.getDuration());
        int duartion = leaves.getDuration().setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        taskService.setVariable(delegateTask.getId(), "duration", duartion);

    }
}